import time
import hashlib
from flask import Blueprint, make_response, request
from query.admin_query import add_one_admin, find_one_admin
from utils.utils import return_model
from utils.index import request_get, return_format


admin = Blueprint('admin', __name__)


@admin.route("/register", methods=['POST'])
def register():
    is_administrators = request_get("is_administrators")
    user_name = request_get("user_name")
    user_pwd = request_get("user_pwd")
    user_img = request_get("user_img")
    mail = request_get("mail")
    cookie_id = hashlib.sha256((user_name + str(int(time.time()))).encode('utf-8')).hexdigest()

    user_info = {
        "user_name": user_name,
        "user_pwd": user_pwd,
        "user_img": user_img,
        "is_administrators": is_administrators,
        "cookie_id": cookie_id,
        "mail": mail,
    }
    find_one_data = find_one_admin({"user_name": user_name})
    if find_one_data["msg"] == "success":
        # 等于空那么证明当前已经存在此用户名，则提示用户当前用户名已注册
        # 不等于空则证明当前用户名还未注册，则继续执行注册逻辑并返回用户名
        if find_one_data["data"] is None:
            add_one_data = add_one_admin(user_info)
            admin_data = add_one_data["data"].admin_to_dict()
            return make_response((return_format("注册成功!", return_model(admin_data, ["user_name", "user_img"]), 200)))
        elif find_one_data["data"] is not None:
            return make_response((return_format("用户名已注册!", None, 204)))
    elif find_one_data["msg"] == "error":
        return make_response((return_format("查询失败!", None, 500)))


@admin.route("/login", methods=['POST'])
def login():
    user_name = request_get("user_name")
    user_pwd = request_get("user_pwd")

    find_one_data = find_one_admin({"user_name": user_name})

    if find_one_data["msg"] == "success":
        # 如果为空则证明当前用户名不存在，如果不为空则说明当前用户名存在即执行对比密码是否相同
        if find_one_data["data"] is None:
            return make_response((return_format("用户名不存在!", None, 204)))
        elif find_one_data["data"] is not None:
            admin_data = find_one_data["data"].admin_to_dict()
            if admin_data["user_pwd"] == user_pwd:
                res = make_response((return_format("登录成功!", return_model(admin_data, ["user_name", "user_img", "is_administrators", "id"]), 200)))
                # 设置cookie的值与过期时间为30天
                res.set_cookie("cookie_id", admin_data["cookie_id"], max_age=60 * 60 * 24 * 30, secure=True, samesite="None", httponly=True)
                return res
            else:
                return make_response((return_format("密码错误!", None, 204)))
    elif find_one_data["msg"] == "error":
        return make_response((return_format("查询失败!", None, 500)))


@admin.route("/init", methods=['POST'])
def init():
    cookie_id = request.cookies.get('cookie_id')
    if cookie_id is None:
        # 如果为空则说明当前用户为登录或cookie过期，则需要重新登录
        return make_response((return_format("登录授权已过期!", None, 204, False)))
    elif cookie_id is not None:
        # 如果不为空则说明当前用户为cookie未过期
        find_one_data = find_one_admin({"cookie_id": cookie_id})
        admin_data = find_one_data["data"].admin_to_dict()
        return make_response((
            return_format("登录成功!", return_model(admin_data, ["user_name", "user_img", "is_administrators", "id"]), 200, False)))


@admin.route("/delete_cookie", methods=['POST'])
def delete_cookie():
    res = make_response((return_format("退出登录成功!", None, 200)))
    res.set_cookie("cookie_id", '', max_age=0, secure=True, samesite="None", httponly=True)
    return res
